﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HARTCalibrationTool.Observers
{
    public class ListViewUpdater : IObserver
    {
        private ListView _listView;
        public ListViewUpdater(ListView listView) 
        { 
            this._listView = listView;
        }

        public void Update(List<string> listStr)
        {
            if (this._listView.InvokeRequired)
            {
                this._listView.Invoke(new Action<List<string>>(Update), listStr);
            }
            else
            {
                /* itemX\#\subitemX\#\data, for exaple: 1#2#0x725E96 --> item:1,subitem:2,data:0x725E96 */

                ListViewItem item = null;
                byte itemNum = 0;
                byte subItemNum = 0;
                string[] strInfo;

                foreach (string str in listStr)
                {
                    strInfo = str.Split('#');

                    if (strInfo.Length == 0)
                    {
                        continue;
                    }

                    if (byte.TryParse(strInfo[0], out itemNum))
                    {
                        item = this._listView.Items[itemNum];
                    }
                    else
                    {
                        continue;
                    }

                    if (byte.TryParse(strInfo[1], out subItemNum))
                    {
                        //item.SubItems[subItemNum].Text = "";
                        item.SubItems[subItemNum].Text = strInfo[2];
                    }
                    else
                    {
                        continue;
                    }
                }
            }
        }
    }
}
